<template>
	<el-form
        ref="validateForm"
        :model="formData"
        :rules="rules"
        label-width="150px"
        class="AddOpenProxyAudit"
    >
        <el-form-item
            label="入口权限"
            prop="accountType"
        >
            <el-col :span="12">
                <el-select disabled :value="0">
                    <el-option label="开启" :value="0">
                    </el-option>
                </el-select>
            </el-col>
        </el-form-item>

        <el-form-item
            label="代理层级归属"
            prop="upProxyType"
        >
            <el-col :span="12">
                <el-select
                    v-model="formData.upProxyType"
                    @change="handleUpProxyTypeChange"
                    :placeholder="
                        $t('agent.rule_select_tip_agent_type')
                    "
                >
                    <el-option label="非总代" :value="0">
                    </el-option>
                    <el-option label="总代" :value="1">
                    </el-option>
                </el-select>
            </el-col>
        </el-form-item>
        <el-form-item
            label="直属上级"
            prop="parentProxyName"
            key="parentProxyName"
            v-if="!isTotalAgent"
        >
            <el-col :span="12">
                <el-input
						v-model="formData.parentProxyName"
						size="medium"
						:placeholder="$t('common.please_enter')"
					></el-input>
            </el-col>
        </el-form-item>
        <el-form-item
            label="同名会员转代"
            prop="memberTransformType"
            key="memberTransformType"
        >
            <el-col :span="12">
                <el-select
                    v-model="formData.memberTransformType"
                    :placeholder="
                        $t('agent.rule_select_tip_agent_type')
                    "
                >
                    <el-option label="不转至同名代理下级" :value="0">
                    </el-option>
                    <el-option :disabled="outlineInfo.commissionModel === 2" label="转至同名代理下级" :value="1">
                    </el-option>
                </el-select>
            </el-col>
        </el-form-item>

        <!-- 总代 form -->
        <div v-if="isTotalAgent">
            <el-form-item
                :label="$t('agent.agent_type') + ':'"
                prop="accountType"
            >
                <el-col :span="12">
                    <el-select
                        disabled
                        v-model="formData.accountType"
                        :placeholder="
                            $t('agent.rule_select_tip_agent_type')
                        "
                    >
                        <el-option
                            v-for="item in accountTypeArr"
                            :key="item.code"
                            :label="item.description"
                            :value="Number(item.code)"
                        ></el-option>
                    </el-select>
                </el-col>
            </el-form-item>
            <el-form-item
                class="current_spetify_item required"
                :label="$t('common.business_model') + ':'"
                :placeholder="$t('common.business_choose_default')"
                prop="businessModel"
            >
                <el-col :span="12">
                    <business-model-selector
                        :hideAllModel="false"
                        disabled
                        v-model="formData.businessModel"
                    />
                </el-col>
            </el-form-item>
            <el-form-item
                class="current_spetify_item required"
                label="取款限制类型:"
                prop="withdrawLimitType"
            >
                <el-col :span="12">
                    <el-select
                        v-model="formData.withdrawLimitType"
                        :placeholder="
                            $t('common.business_choose_default')
                        "
                        disabled
                    >
                        <el-option :value="2" label="流水限制" />
                        <el-option :value="1" label="账单限制" />
                    </el-select>
                </el-col>
            </el-form-item>
            <el-form-item
               prop="commissionModel"
                v-if="parseInt(formData.businessModel) === 1"
                class="current_spetify_item required"
                label="代理分润模式:"
            >
                    <el-col :span="12">
                        <el-select
                            v-model="formData.commissionModel"
                            :placeholder="
                                $t('common.business_choose_default')
                            "
                        >
                            <el-option :value="1" label="占成模式" />
                            <el-option :value="2" label="佣金模式" />
                        </el-select>
                    </el-col>
                </el-form-item>
            <el-form-item
                :label="$t('agent.agent_level_limit') + ':'"
                prop="maxLevel"
            >
                <el-col :span="12">
                    <el-select
                        v-model="formData.maxLevel"
                        :placeholder="
                            $t('agent.rule_select_tip_level_limit')
                        "
                    >
                        <el-option
                            v-for="item in agentLevel"
                            :key="item.id"
                            :label="item.id"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-col>
            </el-form-item>
            <AgentRebates ref="AgentRebates" :isEdit="true" :commissionModel="formData.commissionModel" labelWidth="150px" />
        </div>
        <el-form-item label="申请信息" prop="applyRemark">
            <el-col :span="12">
                <el-input
                    v-model.trim="formData.applyRemark"
                    :rows="4"
                    show-word-limit
                    type="textarea"
                    minlength="4"
                    maxlength="500"
                />
            </el-col>
        </el-form-item>
       
        <div class="info" v-if="!isTotalAgent && formData.memberTransformType === 1" style="margin-left: 150px;">
            申请开启代理入口权限后，同名会员将同步申请转至代理名下。请在【开启代理入口审核】页面审核通过后，开启代理入口权限成功
        </div>
    </el-form>
</template>

<script>
import { rules, accountTypeArr } from './rules.js'
import list from '@/mixins/list'
import BusinessModelSelector from '@/components/Form/BusinessModelSelector.vue'
import AgentRebates from '@/components/AgentRebates'

export default {
	name: 'TotalAgent',
	components: {
		AgentRebates,
		BusinessModelSelector
	},
	mixins: [list],
    props: {
        outlineInfo: {
            type: Object,
            default: () => ({})
        }
    },
	data() {
		return {
			loading: false,
			agentLevel: [],
            parentCommissionMode: undefined,
			formData: {
                upProxyType: 0,
				userName: undefined,
				password: undefined,
				maxLevel: undefined,
				accountType: undefined,
				withdrawLimitType: undefined,
				businessModel: '2',
                commissionModel: 1,
                memberTransformType: 1,
                applyRemark: undefined,
			}
		}
	},

	computed: {
		appIdArr() {
			return this.globalDics.appId || []
		},
		rules() {
			return rules(this.outlineInfo, (res) => {
               
            })
		},
		accountTypeArr,

        isTotalAgent() {
            return this.formData.upProxyType === 1
        }
	},
	watch: {
		// 'formData.businessModel': {
		// 	handler(val) {
		// 		if (val && val === '1') {
		// 			this.formData.withdrawLimitType = '2'
		// 		} else if (val && val === '2') {
		// 			this.formData.withdrawLimitType = '1'
		// 		}
		// 	}
		// }
	},
    created() {
        this.formData.accountType = this.outlineInfo.accountType
        this.formData.businessModel = this.outlineInfo.businessModel + ''
        this.formData.withdrawLimitType = this.outlineInfo.withdrawLimitType
        this.getProxyLevelNameList()
        this.$nextTick(() => {
            this.$refs['AgentRebates'].resetFields()
        })

        if (this.outlineInfo.commissionModel === 2) {
            this.formData.memberTransformType = 0
        }
    },
	methods: {
        handleUpProxyTypeChange(e) {
            this.$refs['AgentRebates'].resetFields()
        },
        getProxyLevelNameList() {
			this.agentLevel = []
			this.$api.getProxylevelnameList().then((res) => {
				if (res?.code === 200) {
					this.agentLevel = Array.isArray(res.data) ? res.data : []
				} else {
					this.agentLevel = []
				}
			})
		},
		formatParams() {
			const params = {
				...this.formData,
				rebateAllotMode: 1,
                merchantId: this.outlineInfo.merchantId,
                userName: this.outlineInfo.userName,
                // 兼容commissionMode
                commissionMode: this.formData.commissionModel
			}

            if (this.isTotalAgent) { 
                params['memberRebateRate'] = this.$refs['AgentRebates'].getValues(['memberPlatform'])[0]
                if (this.formData.commissionModel === 2) {
                    params['commissionRateList'] = this.$refs['AgentRebates'].getValues(['commissionDzRebates'])
                } else {
                    params['proxyRebateRateList'] = this.$refs['AgentRebates'].getValues(['teamRebates', 'teamContribution'])
                }
            }
			return params
		},
		async resetForm() {
            if (this.isTotalAgent) {
                await this.$refs['validateForm'].resetFields()
            }
			await this.$refs['AgentRebates'].resetFields()
		},
		async validate() {
			return Promise.all([
				new Promise((resolve, reject) => {
                    if (this.isTotalAgent) {
                        this.$refs['AgentRebates'].validate((err) => {
                            if (err) {
                                return resolve()
                            }

                            return reject()
                        })
                    } else {
                        return resolve()
                    }
				}),
				new Promise((resolve, reject) => {
					this.$refs['validateForm'].validate((err) => {
						if (err) {
							return resolve()
						}
						return reject()
					})
				})
			])
		},
		async submitForm() {
			try {
				await this.validate()
                if (this.isTotalAgent) {
                    const _rebateRateList = this.$refs['AgentRebates'].getValues()
                    _rebateRateList.forEach(e => {
                        delete e.platformFlag
                        delete e.zhanchengFlag
                        delete e.userType
                    })
                    if (Object.values(_rebateRateList[0]).every((value) => value == 0) &&
                    Object.values(_rebateRateList[1]).every((value)=> value == 0) &&
                    Object.values(_rebateRateList[2]).every((value) => value == 0)) {
                        this.$message.error('全部场馆项目不能全为 0 至少 1 个场馆值>0')
                        return
                    }
                }
				const res = await this.$api.openProxyAddOpenProxyAudit(this.formatParams())
				if (res.code === 200) {
                    this.resetForm()
					return await res.data
				}

                this.$message({
                    message:
                        res?.msg || this.$t('agent.interface_exceptions'),
                    type: 'error'
                })
			} catch (err) {
				if (err === false) return
				throw err
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

